<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { memberFeeConfigListApi, memberFeeConfigUpdateApi } from '@/api/merchantManagement'
import Write from './ComboConfigWrite.vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { memberFeeConfigItem } from '@/api/merchantManagement/types'
import { MemberComboTypeDict, dictToList } from '@/utils/dict'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const {} = tableState
    const res = await memberFeeConfigListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'memberType',
    label: '会员类型',
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        style: {
          width: '50%'
        },
        options: dictToList(MemberComboTypeDict)
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.memberType === 1 ? '商场版' : '商户版'}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'memberName',
    label: '套餐名称',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'string'
      }
    }
  },
  {
    field: 'memberFee',
    label: '套餐价格',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        slots: {
          append: () => <span>元</span>
        }
      }
    }
  },
  {
    field: 'activeCount',
    label: '活动发布次数',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        slots: {
          append: () => <span>次</span>
        }
      }
    }
  },
  {
    field: 'maxInviteAgentCount',
    label: '经纪人数量',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        placeholder: '不填则不限制',
        slots: {
          append: () => <span>人</span>
        }
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{!row.maxInviteAgentCount ? '不限' : row.maxInviteAgentCount}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'singleActiveMerchantCount',
    label: '单活动商户数',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        placeholder: '不填则不限制',
        slots: {
          append: () => <span>家</span>
        }
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{!row.singleActiveMerchantCount ? '不限' : row.singleActiveMerchantCount}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'validMonth',
    label: '有效期',
    formatter: (record: Recordable) => {
      return `${record.validMonth}个月`
    },
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number',
        slots: {
          append: () => <span>月</span>
        }
      }
    }
  },
  {
    field: 'sort',
    label: '排序',
    form: {
      colProps: {
        span: 24
      },
      componentProps: {
        style: {
          width: '50%'
        },
        type: 'number'
      }
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 120,
      slots: {
        default: (data: any) => {
          const row = data.row as memberFeeConfigItem
          return (
            <>
              <ElButton
                v-hasPermi="POST /memberFeeConfig/update"
                type="primary"
                link
                onClick={() => action(row, 'edit')}
              >
                {t('exampleDemo.edit')}
              </ElButton>
              <ElButton
                v-hasPermi="POST /memberFeeConfig/update"
                type="primary"
                link
                onClick={() => updateState(row)}
              >
                {row.showState === 1 ? t('MerchantManagement.hide') : t('MerchantManagement.show')}
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const showDrawer = ref(false)
const drawerTitle = ref('')
const AddAction = () => {
  drawerTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  showDrawer.value = true
  actionType.value = ''
}
const currentRow = ref<memberFeeConfigItem>()
const actionType = ref('')

const updateState = (row: memberFeeConfigItem) => {
  const text = row.showState === 1 ? '确认隐藏该会员费？' : '确认显示该会员费？'
  const success =
    row.showState === 1 ? t('MerchantManagement.hideSuccess') : t('MerchantManagement.showSuccess')
  ElMessageBox.confirm(text, {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(() =>
      memberFeeConfigUpdateApi({
        ...row,
        showState: row.showState === 1 ? 2 : 1
      })
    )
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success(success)
        getList()
      } else {
        ElMessage.error(res.message)
      }
    })
}

const writeRef = ref<ComponentRef<typeof Write>>()

const action = (row: memberFeeConfigItem, type: string) => {
  if (!row.maxInviteAgentCount) {
    row.maxInviteAgentCount = null
  }
  if (!row.singleActiveMerchantCount) {
    row.singleActiveMerchantCount = null
  }
  drawerTitle.value = t('exampleDemo.edit')
  actionType.value = type
  currentRow.value = { ...row }
  showDrawer.value = true
}

const saveLoading = ref(false)

const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  write?.reset()
  showDrawer.value = false
  getList()
}

const onCloseDrawer = () => {
  showDrawer.value = false
  const write = unref(writeRef)
  write?.reset()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3]">
      <div class="mb-10px">
        <ElButton type="success" @click="AddAction">
          <ElIcon><Plus /></ElIcon>
          添加会员套餐
        </ElButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <ElDrawer
      :title="drawerTitle"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="onCloseDrawer"
    >
      <Write ref="writeRef" :form-schema="allSchemas.formSchema" :current-row="currentRow" />

      <template #footer>
        <ElButton @click="onCloseDrawer">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
      </template>
    </ElDrawer>
  </div>
</template>
